#pragma once

#include <iostream>
#include <string>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
using namespace TcpServerModule;
class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }
    void Start()
    {
        _tsvr->InitTcpServer([this](SockPtr sockfd, InetAddr client)
                             { return this->HandlerHttpRequest(sockfd, client); });
        _tsvr->Loop();
    }
    // 处理Http的入口
    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(Loglevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << client.Addr();
        // 获取客户端请求
        std::string httprequest;
        sockfd->Recv(&httprequest);
        std::cout << httprequest;
        HttpRequest req;
        req.Deserialize(httprequest);
        // 测试
        // req.Print();
        std::cout << "用户请求:" << req.Uri() << std::endl;
        HttpResponse res;
        res.Build(req);
        std::string resp_str;
        res.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;
    }
    ~HttpServer()
    {
    }

private:
    std::unique_ptr<TcpServer> _tsvr;
};